package com.Hehong;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.sf.jmyspaceiml.log.Log;

import org.jivesoftware.database.DbConnectionManager;

/**
 * ofuserconnect 数据表管理类
* <p>Title: DbOAuthManager<／p>
* <p>Description: <／p>
* <p>Company: no<／p> 
* @author 陈河宏
* @date 2015年4月1日
 */
public class DbOAuthManager {
	
	public DbOAuthManager(){
		
	}
	
	private static final String GET_USERNAME = "SELECT userName FROM ofuserconnect WHERE authCompany = ? AND connectId = ?";
	private static final String ADD = "INSERT INTO ofuserconnect(userName,authCompany,connectId) VALUES(?,?,?)";
	
	/**
	 * 根据openid和from获取用户名，判断是否openid已经存在
	 */
	public String getUserName(String openid,String from){
		Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String result = null;
        
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(GET_USERNAME);
            pstmt.setString(1, from);
            pstmt.setString(2, openid);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                result =  rs.getString(1);
            } 
        } catch (SQLException sqle) {
        	Log.error(sqle.getMessage());
        } finally {
        	DbConnectionManager.closeConnection(pstmt, con);
        }
        return result;
	}
	
	
	/**
	 * 根据openid和from、username插入到数据表中
	 */
	public boolean add(String openid,String from,String username){
		Connection con = null;
        PreparedStatement pstmt = null;
        
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(ADD);
            int i=1;
            pstmt.setString(i++, username);
            pstmt.setString(i++, from);
            pstmt.setString(i++, openid);
            
            return pstmt.execute();
        } catch (SQLException sqle) {
        	Log.error(sqle.getMessage());
        	return false;
        } finally {
        	DbConnectionManager.closeConnection(pstmt, con);
        }
	}
}
